var {
  timeUtils,
  logUtils,
  randomUtils,
  swipeUtils,
  existContent,
} = require("../../utils/index");
module.exports = {
  watchAd(span, handleNextAd) {
    this.span = span;
    this.handleNextAd = handleNextAd;
    this.init();
  },
  stopAd() {
    sleep(randomUtils.getRandom(2, 3, 1000));
    back();
    sleep(randomUtils.getRandom(2, 3, 1000));
  },
  init() {
    var startTime = Date.now();
    var lastStartTime = Date.now();
    var count = 0;
    while (true) {
      count++;
      if (randomUtils.possible(15, 100)) {
        swipeUtils.swipeUp();
      } else {
        swipeUtils.swipeDown();
      }
      sleep(randomUtils.getRandom(3, 5, 1000));
      if (count % 5 == 0) {
        logUtils.info("已经看了" + hasExec + "/" + this.span);
      }
      var hasExec = timeUtils.hasExec(startTime);

      if (hasExec > 20 && timeUtils.hasExec(lastStartTime) > 10) {
        if (this.isOver()) {
          this.stopAd();
          break;
        } else {
          lastStartTime = Date.now();
        }
      }

      if (hasExec > this.span) {
        if (count % 5 != 0) {
          logUtils.info("已经看了" + hasExec + "/" + this.span);
        }
        this.stopAd();
        break;
      }
    }
  },
  isOver() {
    var content = "任务已完成";
    if (existContent(content)) {
      return true;
    }
    return false;
  },
};
